package com.basic.controller.thread;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ThreadFactoryName implements ThreadFactory {

    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePreFix;

    public ThreadFactoryName() {
        this("basic-project-pool");
    }

    private ThreadFactoryName(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePreFix = name + POOL_NUMBER.getAndIncrement();
    }

    @Override
    public Thread newThread(@NotNull Runnable r) {
        // 此时线程的名字 就是 namePrefix + -thread- + 这个线程池中第几个执行的线程
        final Thread thread = new Thread(group, r, namePreFix + "-thread-" + threadNumber.getAndIncrement(), 0);
        // 判断是否是守护进程，如果是就改为不是守护进程(因为通常我不希望后台任务线程在应用程序的主要部分退出时自动退出)
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }
        // 这是一种防御性编程实践，确保线程以预期的优先级运行。
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }

        return thread;
    }
}
